package com.ruoyi.framework.web.service;

//import com.ruoyi.bantong.domain.BtUser;
import com.ruoyi.bantong.domain.BtOrganization;
import com.ruoyi.bantong.mapper.BtOrganizationMapper;
import com.ruoyi.bantong.service.IBtUserService;
import com.ruoyi.common.core.domain.entity.BtUser;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
@Primary
public class UserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private IBtUserService btUserService;

    @Autowired
    private BtOrganizationMapper btOrganizationMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String type = request.getParameter("type");
        SysUser user = null;
        BtUser btUser = null;
        if ("mobile".equals(type)) {
            btUser = btUserService.selectBtUserByPhone(username);
            if(StringUtils.isNull(btUser)){//查询不到用户直接注册
                this.addBtlUser(username);
                btUser = btUserService.selectBtUserByPhone(username);
            }
        }else {
            user = userService.selectUserByUserName(username);
            if (StringUtils.isNull(user)) {
                log.info("登录用户：{} 不存在.", username);
                throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
            } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
                log.info("登录用户：{} 已被删除.", username);
                throw new BaseException("对不起，您的账号：" + username + " 已被删除");
            } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
                log.info("登录用户：{} 已被停用.", username);
                throw new BaseException("对不起，您的账号：" + username + " 已停用");
            }
            return createLoginUser(user);
        }
        return createLoginUser(btUser);
    }

    public UserDetails createLoginUser(SysUser user)
    {
        return new LoginUser(user, permissionService.getMenuPermission(user));
    }

    public UserDetails createLoginUser(BtUser btUser)
    {
        SysUser user = new SysUser();
        user.setBtUserId(btUser.getUserId());
        user.setUserName(btUser.getPhone());
        user.setPassword("123");
        return new LoginUser(user,btUser);
    }

    private void addBtlUser(String username){
        BtUser btUser = new BtUser();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String orgCode = request.getParameter("orgCode");
        String orgId = request.getParameter("orgId");
        if(!StringUtils.isEmpty(orgCode)){
            BtOrganization btOrganization = btOrganizationMapper.selectBtOrganizationByOrgCode(orgCode);
            if(StringUtils.isNull(btOrganization)){
                throw new CustomException("未查询到机构信息！");
            }
            btUser.setOrgId(btOrganization.getOrgId());
        }

        if(!StringUtils.isEmpty(orgId)){
            btUser.setOrgId(Integer.parseInt(orgId));
        }

        btUser.setPhone(username);
        btUser.setUserLevel(1);//会员等级注册时候默认都设置为后台最低的第一个等级  当前默认一级
        btUserService.insertBtUser(btUser);
    }
}
